<template>
    <div>
        <div>
            <el-form :model="searchForm" label-width="120px">
                <el-form-item label="订单金额">
                    <el-input v-model="searchForm.totalAmount" placeholder="请输入订单金额"></el-input>
                </el-form-item>
                <el-form-item label="评分排序">
                    <el-select v-model="sortOrder" placeholder="选择排序方式">
                        <el-option label="评分升序" :value="1"></el-option>
                        <el-option label="评分降序" :value="-1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">搜索</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-table v-if="Array.isArray(sortedTableData) && sortedTableData.length" :data="sortedTableData" stripe>
                <el-table-column prop="orderId" label="订单号" />
                <el-table-column prop="serviceDetail" label="服务详情">
                    <template #default="scope">
                        <div>
                            <el-button @click="scope.row.isExpanded = !scope.row.isExpanded">
                                {{ scope.row.isExpanded ? '隐藏' : '显示' }} 详情
                            </el-button>
                            <div v-if="scope.row.isExpanded">
                                <div v-if="scope.row.serviceDetail">
                                    <div v-if="parsedDetail = parseServiceDetail(scope.row.serviceDetail)">
                                        服务编号: {{ parsedDetail.serviceId }} <br />
                                        商家编号: {{ parsedDetail.shopId }} <br />
                                        服务名: {{ parsedDetail.serviceName }} <br />
                                        服务价格: {{ parsedDetail.servicePrice }} <br />
                                        服务描述: {{ parsedDetail.details }} <br />
                                        必需品: {{ parseServiceItems(parsedDetail.serviceItems) }} <br />
                                        工时: {{ parsedDetail.estimatedTime }} <br />
                                        服务条款: {{ parsedDetail.terms }} <br />
                                        流程信息: {{ parseProcesses(parsedDetail.serviceProcesses) }} <br />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="支付价格" />
                <el-table-column prop="appointmentTime" label="预约时间" />
                <el-table-column label="订单状态">
                    <template v-slot="scope">
                        {{ checkState(scope.row.orderState) }}
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" />
                <el-table-column label="评价">
                    <template v-slot="{ row }">
                        <el-input type="textarea" :value="row.evaluate" readonly :rows="3"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="评分">
                    <template v-slot="{ row }">
                        <div>
                            <span v-for="star in maxStars" :key="star" :class="['star', { 'filled': star <= row.rating }]">★</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <div v-else>
                <p>没有已完成订单</p>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'OrderFinished',
    data() {
        return {
            maxStars: 5, // 最大星星数量
            userServiceFinished: { list: [] },
            searchForm: {},
            sortOrder: null,
        }
    },
    computed: {
        // 根据排序选择动态生成排序后的表格数据
        sortedTableData() {
            if (!this.userServiceFinished.list) return [];
            return [...this.userServiceFinished.list].sort((a, b) => {
                if (this.sortOrder === 1) {
                    return a.rating - b.rating; // 升序
                } else if (this.sortOrder === -1) {
                    return b.rating - a.rating; // 降序
                }
                return 0; // 不排序
            });
        },
    },
    methods: {
        checkState(state) {
            const states = {
                1: '已完成',
                2: '已取消',
                3: '已关闭',
                4: '进行中',
                5: '待评价',
                6: '待使用',
                7: '待发货',
            };
            return states[state] || '未知状态';
        },
        parseServiceDetail(serviceDetail) {
            try {
                const detail = JSON.parse(serviceDetail);
                detail.serviceItems = detail.serviceItems ? JSON.parse(detail.serviceItems) : [];
                detail.serviceProcesses = detail.serviceProcesses ? JSON.parse(detail.serviceProcesses) : [];
                return detail;
            } catch (error) {
                console.error('解析 serviceDetail 时出错:', error);
                return {}; // 返回空对象以避免渲染错误
            }
        },
        parseServiceItems(serviceItems) {
            if (!serviceItems || serviceItems.length === 0) {
                return '无'; // 如果没有服务项目，显示“无”
            }
            return serviceItems.map(item => {
                return `服务编号: ${item.itemsId}, 数量: ${item.quantity}, 单价: ${item.unitPrice}`;
            }).join(', ');
        },
        parseProcesses(processes) {
            if (!processes || processes.length === 0) {
                return '无'; // 如果没有流程，显示“无”
            }
            return processes.map(item => {
                return `流程编号: ${item.processesId}, 工时: ${item.workingHours}, 单价: ${item.unitPrice}`;
            }).join(', ');
        },
        reset() {
            this.searchForm = {}; // 重置表单
            this.sortOrder = null; // 重置排序
            this.findServiceFinish();
        },
        search() {
            this.$http.get("/order/order/getOrderListShop", {
                params: {
                    totalAmount: this.searchForm.totalAmount,
                    orderState: 1
                }
            }).then(resp => {
                this.userServiceFinished = resp.data.data || { list: [] }; // 确保数据结构一致
            }).catch(error => {
                console.error('搜索订单失败:', error);
            });
        },
        findServiceFinish() {
            this.$http.get("/order/order/getOrderListShop", { params: { orderState: 1 } })
                .then(res => {
                    this.userServiceFinished = res.data.data || { list: [] }; // 确保数据结构一致
                }).catch(error => {
                    console.error('获取已完成订单失败:', error);
                    this.userServiceFinished = { list: [] }; // 如果出错，确保数据结构一致
                });
        },
    },
    created() {
        this.findServiceFinish();
    }
}
</script>

<style scoped>
.star {
    color: lightgray; /* 未填充星星的颜色 */
    font-size: 20px; /* 星星大小 */
    margin-right: 2px; /* 星星之间的间距 */
}
.star.filled {
    color: gold; /* 填充星星的颜色 */
}
</style>